package es.shinra.app.BBDD.Object.DAO;



import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import es.shinra.app.BBDD.Object.Content;
import es.shinra.app.BBDD.Object.Query;
import es.shinra.app.BBDD.Object.iContent;
import es.shinra.app.BBDD.Object.iQuery;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;
import org.xmldb.api.modules.XPathQueryService;


/**
 *
 * @author Huchnet
 */
public class DBManager implements iDBManager{

    private static Collection eCollectionExist=null;
    private static Connection eConnectionJDBC=null;

    private XPathQueryService service;
    private Statement statement;

    private static DBManager aManager=null;

    private iDataSource eDataSource;
    private iXMLDbDataSource aXMLDbDataSource;
    iContent aContent;
    public DBManager(){
        
        eDataSource = new DataSource();
        aXMLDbDataSource = new XMLDbDataSource();
        try {
            eCollectionExist = eDataSource.getCollection();
            eConnectionJDBC = eDataSource.getConnection();
            statement = (Statement) eConnectionJDBC.createStatement();
            service = (XPathQueryService) eCollectionExist.getService("XPathQueryService", "1.0");
            
        } catch (Exception ex) {
             ex.printStackTrace();
        }
    }
    /*
     * Manager con 2 bases de Datos JDBC y EXIST
     */
    public static DBManager getInstance(){

        if (aManager==null || eCollectionExist==null || eConnectionJDBC==null){
           aManager = new DBManager();
           if(aManager.eCollectionExist==null || aManager.eConnectionJDBC==null ){
               return null;
           }
        }
        return aManager;
    }
    /*
     * Manager con Solo JDBC
     */
    public static DBManager getInstanceJDBC(){

        if (aManager==null || eConnectionJDBC==null){
           aManager = new DBManager();
           if(aManager.eConnectionJDBC==null ){
               return null;
           }
        }
        return aManager;
    }
    /*
     * Manager con solo EXIST
     */
    public static DBManager getInstanceExist(){

        if (aManager==null || eCollectionExist==null ){
           aManager = new DBManager();
           if(aManager.eCollectionExist==null  ){
               return null;
           }
        }
        return aManager;
    }
    public iDBActionResult execute(iDBAction eDBAction) {
        
        List eActionIdList=eDBAction.getActionId();
        List eParametersList=eDBAction.getParameters();
        iDBActionResult eActionResult = new DBActionResult();
        for(int i=0; i<eActionIdList.size();i++ ){

            if(((String)eActionIdList.get(i)).equalsIgnoreCase("eXist")){
                ResourceSet aResourceSet=null;
                try {
                    aResourceSet = service.query("doc('books.xml')/bookstore/book/title");
                    
                } catch (XMLDBException ex) {
                    System.out.println("la BBDD eXist no esta encendida:  pon en el terminal-->  cd //Aplications/eXist/bin  ./startup.sh");
                    eActionResult.setException( ex );
                    eActionResult.setErrorMsg( ex.getCause().toString() );
                    break;
                }
                ResourceIterator a = null;
                String eData="";
                try {
                    a = aResourceSet.getIterator();
                    System.out.println("Se carga el Iterator");
                    while(a.hasMoreResources()) {
                        XMLResource r2 = (XMLResource) a.nextResource();
                        //Resource r = a.nextResource();
                        eData=(String)r2.getContent();
                        System.out.println("Iterando"+eData);
                    }

                } catch (XMLDBException ex) {
                }
                aContent = new Content();
                System.out.println("Introduciendo Datos encontrados"+eData);
                aContent.setContent(eData);
                eActionResult.setResult(aContent);

                return eActionResult;
            
            }else if(((String)eActionIdList.get(i)).equalsIgnoreCase("sql")){
                String eData="";
                ResultSet rs=null;
                String nombres[]={"Juan","Pedro","Antonio"};
                String apellidos[]={"Gomez","Lopez","Alvarez"};
                String telefonos[]={"123","456","789"};
                try {
                    statement.executeUpdate("DROP TABLE contacto");
                    statement.executeUpdate("CREATE TABLE contacto (id INT AUTO_INCREMENT, PRIMARY KEY(id), nombre VARCHAR(20), apellidos VARCHAR(20), telefono VARCHAR(20))");
                    for (int e=0;e<nombres.length;i++){
                    
                        statement.executeUpdate("INSERT INTO contacto (nombre, apellidos, telefono) VALUES ('" + nombres[i] + "','" + apellidos[i] + "','" + telefonos[i] + "' )");
                        rs = statement.executeQuery("SELECT * FROM contacto");

                        while (rs.next()){
                            System.out.println("nombre="+rs.getObject("nombre")+
                              ", apellidos="+rs.getObject("apellidos")+
                              ", telefono="+rs.getObject("telefono"));
                            eData=" "+rs.getObject("nombre")+" "+rs.getObject("apellidos")+" "+rs.getObject("telefono");
                            rs.close();
                            aContent = new Content();
                            aContent.setContent(eData);
                            eActionResult.setResult(aContent);
                        }
                    }
                } catch (SQLException ex) {

                }
                return eActionResult;

            }else{
                return null;
            }
        }
        return null;
  }
}
        

             /*
             try {
                while (a.hasMoreResources()) {



                    XMLResource r = (XMLResource) a.nextResource();
                    Image aImage = new Image();
                    ImageHandler aImageHandler = new ImageHandler(aImage);
                    r.getContentAsSAX(aImageHandler);
                    qry = aQuery.getImageInfoFromId(aImage.getId());
                    ResourceSet bResourceSet = null;
                    try {
                        bResourceSet = service.query(qry);
                    } catch (XMLDBException ex) {
                        dbar.setException(ex);
                        dbar.setErrorMsg(ex.getCause().toString());
                        return dbar;
                    }
                    ResourceIterator b = bResourceSet.getIterator();
                    XMLResource r2 = (XMLResource) b.nextResource();
                    Image bImage = new Image();
                    ImageHandler bImageHandler = new ImageHandler(bImage);
                    r2.getContentAsSAX(bImageHandler);
                    qry = aQuery.getImageURLFromId(bImage.getId());
                    ResourceSet cResourceSet = null;
                    try {
                        cResourceSet = service.query(qry);
                    } catch (XMLDBException ex) {
                        dbar.setException(ex);
                        dbar.setErrorMsg(ex.getCause().toString());
                        return dbar;
                    }
                    ResourceIterator c = cResourceSet.getIterator();
                    XMLResource r3 = (XMLResource) c.nextResource();
                    Image cImage = new Image();
                    ImageHandler cImageHandler = new ImageHandler(cImage);
                    r3.getContentAsSAX(cImageHandler);
                    String aResourceLocalPath = cImage.getURL();

                    aResultSet.addElement(TratarMensaje.createSearchResult("image", bImage,aResourceLocalPath, bImage.getTitle()));
                }
             } catch (XMLDBException ex) {}
            
      
          }
          if(((String)aTypeList.get(i)).equalsIgnoreCase("video")){
              
              ResourceSet aResourceSet = null;
                try {
                    aResourceSet = service.query((String) qryList.get(i));
                } catch (XMLDBException ex) {
                    dbar.setException( ex );
                    dbar.setErrorMsg( ex.getCause().toString() );
                    break;
                }
                if(aResourceSet!=null){
                    ResourceIterator a = null;
                    try {
                        a = aResourceSet.getIterator();
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
                    try {
                        while (a.hasMoreResources()) {
                            XMLResource r = (XMLResource) a.nextResource();
                            Video aVideoDescription = new Video();
                            VideoHandler aVideoHandler = new VideoHandler(aVideoDescription);
                            r.getContentAsSAX(aVideoHandler);
                            qry = aQuery.getVideoInfoFromId(aVideoDescription.getId());
                            ResourceSet bResourceSet = service.query(qry);
                            ResourceIterator b = bResourceSet.getIterator();
                            XMLResource r2 = (XMLResource) b.nextResource();
                            Video bVideo = new Video();
                            VideoHandler bVideoHandler = new VideoHandler(bVideo);
                            r2.getContentAsSAX(bVideoHandler);
                            qry = aQuery.getVideoURLFromId(bVideo.getId());
                            ResourceSet cResourceSet = service.query(qry);
                            ResourceIterator c = cResourceSet.getIterator();
                            XMLResource r3 = (XMLResource) c.nextResource();
                            Video cVideo = new Video();
                            VideoHandler cVideoHandler = new VideoHandler(cVideo);
                            r3.getContentAsSAX(cVideoHandler);
                            String aResourceLocalPath = cVideo.getURL();
                            aResultSet.addElement(TratarMensaje.createSearchResult("video", bVideo, aResourceLocalPath, bVideo.getTitle()));
                        }
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
              }

          }
          if(((String)aTypeList.get(i)).equalsIgnoreCase("notice")){
                
                ResourceSet aResourceSet = null;
                try {
                    aResourceSet = service.query((String) qryList.get(i));
                } catch (XMLDBException ex) {
                    dbar.setException( ex );
                    dbar.setErrorMsg( ex.getCause().toString() );
                    break;
                }
                if(aResourceSet!=null){
                    ResourceIterator a = null;
                    try {
                        a = aResourceSet.getIterator();
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
                    try {
                        while (a.hasMoreResources()) {
                            XMLResource r = (XMLResource) a.nextResource();
                            Notice aNoticeDescription = new Notice();
                            NoticeHandler aNoticeHandler = new NoticeHandler(aNoticeDescription);
                            r.getContentAsSAX(aNoticeHandler);
                            List arrayImage = aNoticeDescription.getURL();
                            String aResourceLocalPath;
                            aQuery.loadQuerys();
                            for(int e=0;e<arrayImage.size();e++){
                                qry = aQuery.getImageIdFromURL("\""+(String)arrayImage.get(e)+"\"");
                                aResourceLocalPath=(String)arrayImage.get(e);
                                ResourceSet bResourceSet = service.query(qry);
                                ResourceIterator b = bResourceSet.getIterator();
                                XMLResource r2 = (XMLResource) b.nextResource();
                                Image bImage = new Image();
                                ImageHandler bImageHandler = new ImageHandler(bImage);
                                r2.getContentAsSAX(bImageHandler);

                                qry = aQuery.getImageInfoFromId(bImage.getId());
                                ResourceSet cResourceSet = service.query(qry);
                                ResourceIterator c = cResourceSet.getIterator();
                                XMLResource r3 = (XMLResource) c.nextResource();
                                Image cImage = new Image();
                                ImageHandler cImageHandler = new ImageHandler(cImage);
                                r3.getContentAsSAX(cImageHandler);

                                aResultSet.addElement(TratarMensaje.createSearchResult("image", cImage, aResourceLocalPath, cImage.getTitle()));
                            }

                        }
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
                }else{
                    
                }
        }
        if(((String)aTypeList.get(i)).equalsIgnoreCase("imageupdatenew")){
            String id=null;
            ResourceSet aResourceSet = null;
            try {
                aResourceSet = service.query((String) qryList.get(i));
            } catch (XMLDBException ex) {
                dbar.setException( ex );
                dbar.setErrorMsg( ex.getCause().toString() );
                break;
            }
            if(aResourceSet!=null){
                ResourceIterator a = null;
                try {
                    a = aResourceSet.getIterator();
                } catch (XMLDBException ex) {
                    ex.printStackTrace();
                }
                try {
                    while (a.hasMoreResources()) {
                       XMLResource r = (XMLResource) a.nextResource();
                       Image aImage = new Image();
                       ImageHandler aImageHandler = new ImageHandler(aImage);
                       r.getContentAsSAX(aImageHandler);
                       id = aImage.getNextID();
                    }
                } catch (XMLDBException ex) {
                    ex.printStackTrace();
                }
                if(id!=null){
                    qry=aQuery.getAddBasicImage(id,(String)aTypeList.get(i+1) ,(String)aTypeList.get(i+2));
                    try {
                        service.query(qry);
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
                    
                }
            }
            return null;
        }
        if(((String)aTypeList.get(i)).equalsIgnoreCase("videoupdatenew")){
            String id=null;
            ResourceSet aResourceSet = null;
            try {
                aResourceSet = service.query((String) qryList.get(i));
            } catch (XMLDBException ex) {
                dbar.setException( ex );
                dbar.setErrorMsg( ex.getCause().toString() );
                break;
            }
            if(aResourceSet!=null){
                ResourceIterator a = null;
                try {
                    a = aResourceSet.getIterator();
                } catch (XMLDBException ex) {
                    ex.printStackTrace();
                }
                try {
                    while (a.hasMoreResources()) {
                       XMLResource r = (XMLResource) a.nextResource();
                       Video aVideo = new Video();
                       VideoHandler aVideoHandler = new VideoHandler(aVideo);
                       r.getContentAsSAX(aVideoHandler);

                       id = aVideo.getNextID();
                       
                    }
                } catch (XMLDBException ex) {
                    ex.printStackTrace();
                }
                if(id!=null){
                    qry=aQuery.getAddBasicVideo(id,(String)aTypeList.get(i+1) ,(String)aTypeList.get(i+2));
                    try {
                        service.query(qry);
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
                    
                }
            }
            return null;
        }
        if(((String)aTypeList.get(i)).equalsIgnoreCase("userupdatenew")){
            boolean aBreak=true;
            String id=null;
            qry=aQuery.getUserInfoFromOwner((String)aTypeList.get(i+1));
            ResourceSet aResourceSet = null;
            try {
                aResourceSet = service.query(qry);
            } catch (XMLDBException ex) {
                dbar.setException( ex );
                dbar.setErrorMsg( ex.getCause().toString() );
                break;
            }
            if(aResourceSet!=null){
                ResourceIterator a = null;
                try {
                    a = aResourceSet.getIterator();
                } catch (XMLDBException ex) {
                    ex.printStackTrace();
                }
                try {
                    while (a.hasMoreResources()) {
                       XMLResource r = (XMLResource) a.nextResource();
                       User aUser = new User();
                       UserHandler aUserHandler = new UserHandler(aUser);
                       r.getContentAsSAX(aUserHandler);
                       if(aUser.getId().equalsIgnoreCase((String)aTypeList.get(i+1))){
                           aBreak=false;
                       }

                    }
                } catch (XMLDBException ex) {
                    ex.printStackTrace();
                }
            }
            if(aBreak){
                try {
                    aResourceSet = service.query((String) qryList.get(i));
                } catch (XMLDBException ex) {
                    dbar.setException( ex );
                    dbar.setErrorMsg( ex.getCause().toString() );
                    break;
                }
                if(aResourceSet!=null){
                    ResourceIterator a = null;
                    try {
                        a = aResourceSet.getIterator();
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
                    try {
                        while (a.hasMoreResources()) {
                           XMLResource r = (XMLResource) a.nextResource();
                           User aUser = new User();
                           UserHandler aUserHandler = new UserHandler(aUser);
                           r.getContentAsSAX(aUserHandler);
                           id = aUser.getNextID();

                        }
                    } catch (XMLDBException ex) {
                        ex.printStackTrace();
                    }
                    if(id!=null){
                        qry=aQuery.getAddUser(id, "firsname", "lastname", "nickname",(String)aTypeList.get(i+2) , (String)aTypeList.get(i+1));
                        try {
                            service.query(qry);
                        } catch (XMLDBException ex) {
                            ex.printStackTrace();
                        }
                        
                    }
                }
            }
            return null;
        }

        if(((String)aTypeList.get(i)).equalsIgnoreCase("update")){
           try {
                service.query((String) qryList.get(i));
                
           } catch (XMLDBException ex) {
                ex.printStackTrace();
           }
        }
        if(((String)aTypeList.get(i)).equalsIgnoreCase("imageid")){
            ResourceSet aResourceSet = null;
            
             try {
                
                aResourceSet = service.query((String)qryList.get(i));
             } catch (XMLDBException ex) {
                dbar.setException( ex );
                dbar.setErrorMsg( ex.getCause().toString() );
                break;
             }
             ResourceIterator a = null;
             try {
                a = aResourceSet.getIterator();
             } catch (XMLDBException ex) {

             }
             try {
                while (a.hasMoreResources()) {
                    XMLResource r = (XMLResource) a.nextResource();
                    Image aImage = new Image();
                    ImageHandler aImageHandler = new ImageHandler(aImage);
                    r.getContentAsSAX(aImageHandler);
                    
                    dbar.setStringResult(aImage.getId());
                }
             } catch (XMLDBException ex) {
                ex.printStackTrace();
             }
        }if(((String)aTypeList.get(i)).equalsIgnoreCase("videoid")){
            ResourceSet aResourceSet = null;

             try {
                
                aResourceSet = service.query((String)qryList.get(i));
             } catch (XMLDBException ex) {
                dbar.setException( ex );
                dbar.setErrorMsg( ex.getCause().toString() );
                break;
             }
             ResourceIterator a = null;
             try {
                a = aResourceSet.getIterator();
             } catch (XMLDBException ex) {

             }
             try {
                while (a.hasMoreResources()) {
                    XMLResource r = (XMLResource) a.nextResource();
                    Video aVideo = new Video();
                    VideoHandler aVideoHandler = new VideoHandler(aVideo);
                    r.getContentAsSAX(aVideoHandler);

                    dbar.setStringResult(aVideo.getId());
                }
             } catch (XMLDBException ex) {
                ex.printStackTrace();
             }
        }if(((String)aTypeList.get(i)).equalsIgnoreCase("imageItem")){
            ResourceSet aResourceSet = null;

             try {
                
                aResourceSet = service.query((String)qryList.get(i));
             } catch (XMLDBException ex) {
                dbar.setException( ex );
                dbar.setErrorMsg( ex.getCause().toString() );
                break;
             }
             ResourceIterator a = null;
             try {
                a = aResourceSet.getIterator();
             } catch (XMLDBException ex) {

             }
             try {
                while (a.hasMoreResources()) {
                    XMLResource r = (XMLResource) a.nextResource();
                    Image aImage = new Image();
                    ImageHandler aImageHandler = new ImageHandler(aImage);
                    r.getContentAsSAX(aImageHandler);

                    dbar.setItemDescriptor(aImage);
                }
             } catch (XMLDBException ex) {
                ex.printStackTrace();
             }
        }if(((String)aTypeList.get(i)).equalsIgnoreCase("videoItem")){
            ResourceSet aResourceSet = null;

             try {
                
                aResourceSet = service.query((String)qryList.get(i));
             } catch (XMLDBException ex) {
                dbar.setException( ex );
                dbar.setErrorMsg( ex.getCause().toString() );
                break;
             }
             ResourceIterator a = null;
             try {
                a = aResourceSet.getIterator();
             } catch (XMLDBException ex) {

             }
             try {
                while (a.hasMoreResources()) {
                    XMLResource r = (XMLResource) a.nextResource();
                    Video aVideo = new Video();
                    VideoHandler aVideoHandler = new VideoHandler(aVideo);
                    r.getContentAsSAX(aVideoHandler);

                    dbar.setItemDescriptor(aVideo);
                }
             } catch (XMLDBException ex) {
                ex.printStackTrace();
             }
        }



      }

      dbar.setResult(aResultSet);
      return dbar;
  
    }*/
 
